'use strict'
const { Product, Op } = require('../moudl')
let fn_list = async ctx => {

    let keyword = ctx.request.query.keyword || ''

    if (keyword){
        let list = await Product.findAll({
            where:{
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { head: keyword },
                    { digest: keyword },
                    { details: keyword },
                    { classify: keyword },
                    { anthour: keyword },
                ]
            },
            order: ['id']
        })
        ctx.body = list;
    }else{
        let list = await Product.findAll({
            order: ['id']
        })
        ctx.body = list
    }
}

let fn_query = async ctx=>{
    let id = ctx.request.params.id
    let list = await Product.findAll({
        where:{
            id:id
        }
    })
    ctx.body=list
}

let fn_post = async ctx =>{
    let data = ctx.request.body
    await Product.create({
        head:data.head,
        digest:data.digest,
        details:data.details,
        classify:data.classify,
        anthour:data.anthour,

    })
    let arr = await Product.findAll()
    ctx.body = arr
}

let fn_put = async ctx=>{
    let id = ctx.request.params.id
    let data = ctx.request.body
    await Product.update({
        head:data.head,
        digest:data.digest,
        classify:data.classify,
        anthour:data.anthour,
    },{where:{
        id:id
    }
    })
    let arr = await Product.findAll()
    ctx.body = arr
}


let fn_delete = async ctx=>{
    let id = ctx.request.params.id
    await Product.destroy({
        where:{
            id:id
        }
    })
    ctx.body = id
}

module.exports = {
    'get /product': fn_list,
    'get /product/:id': fn_query,
    'post /product': fn_post,
    'put /product/:id': fn_put,
    'delete /product/:id': fn_delete
}